package sales

import (
	"LogisticsPort/model"
	"LogisticsPort/sql"
	"encoding/json"
	"errors"
	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
	"sort"
)

func analyze(r *gin.RouterGroup) {
	analyze := r.Group("/analyze")
	{
		/*analyze.POST(sql.RequestAdd, )
		analyze.POST(sql.RequestUpdate, )
		analyze.GET(sql.RequestData, )*/
		analyze.GET(sql.RequestList, customerAnalyze)
		analyze.GET(sql.RequestData, customerAnalyzeDetail)
		/*analyze.GET(sql.RequestDelete, )*/
	}
}
func customerAnalyze(c *gin.Context) {
	var customerList []model.Customer
	sql.HttpHandle(sql.GET, c, func(db *gorm.DB) (*gorm.DB, interface{}) {
		productName := c.Query("productName")
		db = db.Where("product_str LIKE ? AND name NOT LIKE ?", "%"+productName+"%", "物 %").
			Preload("SalesStatisticsProduct", func(db *gorm.DB) *gorm.DB {
				db = db.Where("CONCAT(factory_no,product_name) LIKE ?", "%"+productName+"%").
					Order("date DESC")
				return db
			}).
			Find(&customerList)
		less := func(i, j int) bool {
			if len(customerList[i].SalesStatisticsProduct) > 0 && len(customerList[j].SalesStatisticsProduct) > 0 {
				return customerList[i].SalesStatisticsProduct[0].Date > customerList[j].SalesStatisticsProduct[0].Date
			} else if len(customerList[i].SalesStatisticsProduct) > 0 && len(customerList[j].SalesStatisticsProduct) == 0 {
				return true
			} else if len(customerList[i].SalesStatisticsProduct) == 0 && len(customerList[j].SalesStatisticsProduct) > 0 {
				return false
			}
			return false
		}
		sort.Slice(customerList, less)
		return db, customerList
	})
}

func customerAnalyzeDetail(c *gin.Context) {
	var customer model.Customer
	sql.HttpHandle(sql.GET, c, func(db *gorm.DB) (*gorm.DB, interface{}) {
		if id := c.Query("id"); id != "" {
			db = db.Where("customer.id = ?", id)
		} else {
			db.Error = errors.New(sql.ErrorParams)
			return db, nil
		}
		db.
			Preload("SalesStatisticsProduct", func(db *gorm.DB) *gorm.DB {
				db = db.Select("sales_statistics_product.*,product.factory_no,product.product_name").
					Joins("left join product ON product.id = sales_statistics_product.product_id").
					Order("date DESC")
				return db
			}).
			First(&customer)
		json.Unmarshal([]byte(customer.ProductStr), &customer.ProductList)
		return db, customer
	})
}
